import 'dart:async';
import 'dart:io';
import 'dart:ui';

import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/localization_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/controller/theme_controller.dart';
import 'package:efood_multivendor/helper/fcm_helper.dart';
import 'package:efood_multivendor/helper/notification_helper.dart';
import 'package:efood_multivendor/helper/responsive_helper.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/theme/dark_theme.dart';
import 'package:efood_multivendor/theme/light_theme.dart';
import 'package:efood_multivendor/util/app_constants.dart';
import 'package:efood_multivendor/util/messages.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_strategy/url_strategy.dart';

import 'controller/location_controller.dart';
import 'helper/get_di.dart' as di;
import 'view/base/service_unavailable_screen.dart';

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> main() async {
  runZonedGuarded<Future<void>>(() async {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    if (ResponsiveHelper.isMobilePhone()) {
      HttpOverrides.global = new MyHttpOverrides();
    }
    setPathUrlStrategy();
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
    FlutterError.onError = (errorDetails) {
      FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
    };
    Map<String, Map<String, String>> _languages = await di.init();
    try {
      if (GetPlatform.isMobile) {
        await NotificationHelper.initializeForeground(
            flutterLocalNotificationsPlugin);
        FirebaseMessaging.onBackgroundMessage(
            firebaseMessagingBackgroundHandler);
      }
    } catch (e) {}
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
        .then((_) => runApp(MyApp(
              languages: _languages,
            )));
  }, (error, stack) => FirebaseCrashlytics.instance.recordError(error, stack));
}

class MyApp extends StatefulWidget {
  final Map<String, Map<String, String>> languages;

  MyApp({required this.languages});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  final dynamicLink = FirebaseDynamicLinks.instance;
  late AuthController _authController;

  @override
  void initState() {
    getVersion();
    WidgetsBinding.instance.addObserver(this);
    _updateLocation();
    _authController = Get.find<AuthController>();
    _authController.updateToken();
    FirebaseHelper.instance
        .onTokenChanged(onTokenRefresh: _authController.updateDevicesToken);

    super.initState();
  }

  Future<void> getVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    Get.find<SplashController>().setVersion(packageInfo.version);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      //  后台切前台
      _updateLocation();
    } else if (state == AppLifecycleState.paused) {
      //  前台切后台
      _updateLocation();
    }
  }

  // bool _isRequestingLocation = false;

  // 更新当前位置
  Future<void> _updateLocation() async {
    // if (_isRequestingLocation == true) return;
    // _isRequestingLocation = true;
    try {
      await Get.find<LocationController>()
          .getCurrentLocation(false, isNativePicMap: false, isShowToast: false);
    } finally {
      // _isRequestingLocation = false;
    }
  }

  @override
  void dispose() {
    FirebaseHelper.instance.tearDown();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ThemeController>(builder: (themeController) {
      return GetBuilder<LocalizationController>(builder: (localizeController) {
        return GetBuilder<LocationController>(builder: (locationController) {
          return GetBuilder<SplashController>(builder: (splashController) {
            bool isServiceCannotUse =
                (locationController.isServiceAble == false) &&
                    (splashController.configModel?.deadzoneAvailableOrder == 1);
            return (GetPlatform.isWeb && splashController.configModel == null)
                ? SizedBox()
                : GetMaterialApp(
                    builder: (context, child) {
                      return MediaQuery(
                        data: MediaQuery.of(context).copyWith(
                            textScaler:
                                TextScaler.linear(1.0)), // Locks font size
                        child: Stack(
                          children: [
                            child ?? SizedBox.shrink(),
                            if (isServiceCannotUse) ...[
                              Positioned(
                                  left: 0,
                                  top: 0,
                                  right: 0,
                                  bottom: 0,
                                  child: ServiceUnavailableScreen()),
                            ]
                          ],
                        ),
                      );
                    },
                    title: AppConstants.APP_NAME,
                    debugShowCheckedModeBanner: false,
                    navigatorKey: Get.key,
                    scrollBehavior: MaterialScrollBehavior().copyWith(
                      dragDevices: {
                        PointerDeviceKind.mouse,
                        PointerDeviceKind.touch
                      },
                    ),
                    theme: themeController.darkTheme ? dark : light,
                    locale: localizeController.locale,
                    translations: Messages(languages: widget.languages),
                    fallbackLocale: Locale(
                      AppConstants.languages[0].languageCode!,
                      AppConstants.languages[0].countryCode,
                    ),
                    initialRoute: RouteHelper.getSplashRoute(),
                    getPages: RouteHelper.routes,
                    defaultTransition: Transition.topLevel,
                    transitionDuration: Duration(milliseconds: 500),
                  );
          });
        });
      });
    });
  }
}

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
  }
}
